package com.itheima.task;

import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class OssCleanupTask {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;

    @Scheduled(cron = "* * 2 * * ?")
    public void cleanUncommittedImages() {
        Set<String> uncommitted = redisTemplate.opsForSet().difference("uploadedImages", "committedImages");
        if (uncommitted != null) {
            uncommitted.forEach(fullUrl -> {
                // 提取OSS对象名：从URL最后一个/后截取
                String objectName = fullUrl.substring(fullUrl.lastIndexOf("/") + 1);
                try {
                    aliOssUtil.delete(objectName); // ✅ 传递正确参数
                    redisTemplate.opsForSet().remove("uploadedImages", fullUrl);
                    log.info("已清理未提交图片：{}", fullUrl);
                } catch (Exception e) {
                    log.error("删除图片失败：{}", fullUrl, e);
                }
            });
        }
    }
}
